<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="78px">
        <el-form-item label="产品">
          <el-select
            v-model="searchParam.productCode"
            placeholder="请选择产品"
            clearable
          >
            <el-option
              v-for="item in productList"
              :key="`${item.materialCode}`"
              :label="`${item.materialName}`"
              :value="`${item.materialCode}`"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文档">
          <el-input
            v-model="searchParam.docNo"
            placeholder="请输入文档编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="handeleReset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
          ><i-ep-delete />删除</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        @sort-change="onTableSortChanged"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="文档编号"
          prop="docNo"
          min-width="120"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="文档名称"
          prop="docName"
          min-width="120"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="产品"
          prop="productName"
          align="left"
          min-width="150"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="版本号"
          prop="docVersionNo"
          min-width="100"
          show-overflow-tooltip
          align="center"
          sortable
        />
        <el-table-column
          v-if="docType == 2"
          label="存储位置"
          prop="path"
          min-width="100"
          show-overflow-tooltip
          sortable
        />
        <el-table-column fixed="right" label="操作" width="240" align="center">
          <template #default="scope">
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="查看"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialogdetail(scope.row)"
                ><i-ep-search />
              </el-button>
            </el-tooltip>
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="编辑"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialog(scope.row)"
                ><i-ep-edit
              /></el-button>
            </el-tooltip>
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="删除"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="deleteItem(scope.row.id)"
                ><i-ep-delete
              /></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <moldelectronic-documents-edit
      :assetTypeId="assetTypeId"
      :visible="addDialog.visible"
      :docType="addDialog.docType"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { filterOrder } from "@/utils/commonHooks";
defineOptions({
  name: "EAMMOLDGENERALDOCUMENT",
  inheritAttrs: false,
});
// 目录树显隐
const showTree = ref(true);
const handelTree = () => {
  showTree.value = !showTree.value;
};

// 定义按钮
let docType = ref("1");

const radioChange = (e) => {
  docType.value = e;
  searchParam.value.docType = e;
  // searchParam.value.assetTypeId = "";
  searchParam.value.makerId = "";
  searchParam.value.brandId = "";
  searchParam.value.docNo = "";
  searchParam.value.modelNo = "";
  getTableList();
  addDialog.docType = e;
};

// 请求参数
let requestApi = "/eam/eamCommonDoc/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = reactive({
  sort: {
    column: "",
    orderBy: "",
  },
});

// 初始化搜索参数数据
const searchParamInit = {
  assetTypeId: "",
  makerId: "",
  brandId: "",
  docNo: "",
  docType: docType.value,
  assetKind: "3",
};

const deleteParam = {
  api: "/eam/eamCommonDoc/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

// 排序
// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  console.log(prop, order);

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}
// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });

onMounted(() => {
  getTableList();
});

const addDialog = reactive({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  docType: "1",
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/eam/eamCommonDoc/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开资产型号表单弹窗 */
const assetTypeId = ref("");
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改模具文档";
    getInfo(roleObj.id);
  } else {
    assetTypeId.value = searchParam.value.assetTypeId;
    addDialog.title = "新增模具文档";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开资产型号表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "资产型号详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean, docType: string) {
  addDialog.visible = value;
  searchParam.value.docType = docType;
  search();
  if (!value) {
    addDialog.data = {};
  }
}

// 导入excel
const uploadApi = "/eam/eamCommonDoc/upload";
const excelBox = ref(false);
const uploadBtn = ref(false);
const uploadFile = ref("");
const fileName = ref("");

function excelBoxOpen() {
  excelBox.value = true;
}

function getfilepath(e: any) {
  const file = e.target.files[0];
  fileName.value = file.name;
  uploadFile.value = file;
  uploadBtn.value = false;
}

function upload() {
  if (!uploadFile.value) {
    ElMessage({
      type: "warning",
      message: "请选择文件！",
    });
    return;
  }

  let formdata = new FormData();
  formdata.append("file", uploadFile.value);
  let config = { headers: { "Content-Type": "multipart/form-data" } };
  request
    .post(uploadApi, formdata, config)
    .then((res) => {
      ElMessage({
        type: "success",
        message: "上传成功！",
      });

      excelBox.value = false;
      uploadBtn.value = true;
      search();
    })
    .catch((error) => {
      console.log(error);
    });
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/eam/eamCommonDoc/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}

// 重置按钮
const handeleReset = () => {
  searchParam.value.docType = docType.value;
  searchParam.value.assetTypeId = "";
  searchParam.value.makerId = "";
  searchParam.value.productCode = "";

  searchParam.value.brandId = "";
  searchParam.value.docNo = "";
  searchParam.value.modelNo = "";
  search();
};

onMounted(() => {
  getProductList();
});
const productList: any = ref([]);

const getProductList = async () => {
  // 获取内容树
  await request({
    url: "/mdm/mdmmaterial/getList",
    method: "POST",
    data: { materialType: "3" },
  }).then((res) => {
    productList.value = res.data;
  });
};
</script>
<style scoped lang="scss">
@media only screen and (max-width: 768px) {
  .el-col-xs-24 {
    padding-right: 10px !important;
  }
}
</style>
